#!/bin/bash

help() {
  echo "Usage:"
  echo "  zmicro config sevice <service_path> [...options]"
  echo ""
  echo "    -d, --delete    Delete service path"
  echo "    -o, --override  Override service path"
}

core() {
  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2
    case $key in
      -h | --help)
        help
        exit 0
        ;;
      -d | --delete)
        os::set_var delete true
        shift
        ;;
      -o | --override)
        os::set_var override true 
        shift
        ;;
      --tmp-start)
        os::set_var tmp_start true 
        shift
        ;;
      --tmp-end)
        os::set_var tmp_end true 
        shift
        ;;
      *)
        if [ "$(string::match $key ^-)" = "true" ]; then
          echo "ERROR: unknown parameter \"$key\""
          help
          exit 1
        fi

        eval service_path=$key
        shift
        ;;
    esac
  done

  # local service_path=$1
  if [ "$service_path" = "" ]; then
    log::error "custom service path is required"
    log::error ""
    
    help
    exit 1
  fi

  if [ "$service_path" = "." ]; then
    service_path=$PWD
  fi
  
  local new_zmicro_service_path=""
  if [ "$delete" = "true" ]; then
    # delete
    new_zmicro_service_path=$(string::replace $ZMICRO_SERVICES_PATH ${service_path}:)
  elif [ "$override" = "true" ]; then
    # override
    new_zmicro_service_path=$service_path
  elif [ "$tmp_start" = "true" ]; then
    # backup
    if [ "$(zmicro config get ZMICRO_SERVICES_PATH_BAK)" != "" ]; then
      log::warn "found ZMICRO_SERVICES_PATH_BAK, not clean last"
      exit 0
    fi

    new_zmicro_service_path=$service_path
    zmicro config set ZMICRO_SERVICES_PATH_BAK $ZMICRO_SERVICES_PATH
  elif [ "$tmp_end" = "true" ]; then
    # recover
    if [ "$(zmicro config get ZMICRO_SERVICES_PATH_BAK)" = "" ]; then
      log::error "zmicro config service recover backup failed, not found ZMICRO_SERVICES_PATH_BAK"
      exit 1
    fi

    zmicro config set ZMICRO_SERVICES_PATH $(zmicro config get ZMICRO_SERVICES_PATH_BAK)
    zmicro config remove ZMICRO_SERVICES_PATH_BAK
    exit 0
  else
    # add
    new_zmicro_service_path="$service_path:$ZMICRO_SERVICES_PATH"
  fi

  if [ -n "$new_zmicro_service_path" ]; then
    log::debug "config service new path: $new_zmicro_service_path"

    zmicro config set ZMICRO_SERVICES_PATH $new_zmicro_service_path
  fi
}

run() {
  core $@
}

run $@
